package com.marvels.financial.pay.hlbpay.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.marvels.approve.credit.service.CreditReportService;
import com.marvels.approve.process.dto.LaAttachAtmeTypeViewDTO;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.dto.pay.McfeRepaymentTradeDetails;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.GenerateReqNoUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.pay.dao.McfeRepaymentTradeDetailsMapper;
import com.marvels.financial.pay.hlbpay.dao.McfeHlbUserInfoMapper;
import com.marvels.financial.pay.hlbpay.dto.HlbBindCardDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbDirectPaymentDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbDirectPaymentQueryDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbPrebindCardDTO;
import com.marvels.financial.pay.hlbpay.dto.HlbReturnDTO;
import com.marvels.financial.pay.hlbpay.dto.McfeHlbUserInfo;
import com.marvels.financial.pay.hlbpay.dto.config.HlbConfig;
import com.marvels.financial.pay.hlbpay.dto.request.MerchantUserUploadVo;
import com.marvels.financial.pay.hlbpay.service.HlbPayApi;
import com.marvels.financial.pay.hlbpay.util.HlbPayUtil;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class HlbPayService implements HlbPayApi {

	@Value("${platform.name}")
	String platformName;

	@Autowired
	private CreditReportService creditReportService;
	
	@Autowired
	private McfeHlbUserInfoMapper hlbUserInfoMapper;
	
	@Autowired
	private McfeRepaymentTradeDetailsMapper mcfeRepaymentTradeDetailsMapper;
	/**
	 * 绑卡发送短信
	 */
	@Override
	public Map<String, Object> prebindCard(HlbPrebindCardDTO bindCardDTO) throws MarvelsBusinessException {
		return HlbPayUtil.prebindCard(bindCardDTO);
	}

	/**
	 * 确认绑卡
	 */
	@Override
	public Map<String, Object> bindCard(HlbBindCardDTO bindCardDTO) throws MarvelsBusinessException {
		return HlbPayUtil.bindCard(bindCardDTO);
	}

	/**
	 * 协议代扣
	 */
	@Override
	public Map<String, Object> directPayment(HlbDirectPaymentDTO directPaymentDTO) throws MarvelsBusinessException {
		directPaymentDTO.setAppName(platformName);
		return HlbPayUtil.directPayment(directPaymentDTO);
	}

	/**
	 * 代扣结果查询
	 */
	@Override
	public Map<String, Object> directPaymentQuery(HlbDirectPaymentQueryDTO directPaymentQueryDTO)
			throws MarvelsBusinessException {
		return HlbPayUtil.directPaymentQuery(directPaymentQueryDTO);
	}

	/**
	 * 合利宝代付比较特殊
	 * 1.先注册用户（已经注册过的客户可以直接代付）
	 * 2.再上传资质信息
	 * 3.再查询注册状态
	 * 4.用户状态为成功，才调用代付
	 */
	@Override
	public Map<String, Object> pay(McfeRepaymentTradeDetails tradeDetail) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(StrUtil.isNotBlank(tradeDetail.getHlbUserId())){
			// 用户已经注册，用用户id直接代付
			MarvelsLogUtil.getInstance().info("客户已经在合利宝注册，直接代付");
			return HlbPayUtil.pay(tradeDetail);
		}else{
			MarvelsLogUtil.getInstance().info("客户未在合利宝注册，先进行注册");
			// 1.用户未注册，先进行注册
			HlbReturnDTO registerResult = HlbPayUtil.userRegister(tradeDetail);
			// 注册落库
			Map<String, Object> data = (Map<String, Object>) registerResult.getData();
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
			McfeHlbUserInfo mcfeHlbUserInfo = new McfeHlbUserInfo();
			mcfeHlbUserInfo.setIdNumber(tradeDetail.getIdNumber());
			mcfeHlbUserInfo.setMerchantNo(hlbConfig.getMerchantNo());
			mcfeHlbUserInfo.setOrderId(tradeDetail.getPayOrderNumber());
			mcfeHlbUserInfo.setStatus(data == null ? null : data.get("userStatus").toString());
			mcfeHlbUserInfo.setUserId(data == null ? null : data.get("userId").toString());
			hlbUserInfoMapper.insertSelective(mcfeHlbUserInfo);
			if(StrUtil.equals(registerResult.getCode(), "-1")){
				// 注册失败直接结束
				result.put("result", "-1");
        		result.put("errorCode", MarvelsConstant.FAILED);
				result.put("errorMsg", registerResult.getMsg());
				return result;
			}
			// 2.资质上传
			try {
				List<LaAttachAtmeTypeViewDTO> attachList = creditReportService.getAttachmentsByViewKey(tradeDetail.getLoanId());
				//身份证正面
				MerchantUserUploadVo frontVo = new MerchantUserUploadVo();
				frontVo.setP1_bizType("UploadCredential");
				frontVo.setP3_orderId(IdUtil.simpleUUID());
				frontVo.setP4_userId(StrUtil.toString(data.get("userId")));
				frontVo.setP6_credentialType("FRONT_OF_ID_CARD");
				HlbReturnDTO frontResult = HlbPayUtil.userUpload(frontVo, attachList.get(0).getLaAttachmentDTOList().get(0).getFileLocation());
				if(!StrUtil.equals(frontResult.getCode(), "0")){
					result.put("result", "-1");
	        		result.put("errorCode", MarvelsConstant.FAILED);
					result.put("errorMsg", "用户资质【正面】上传失败");
					return result;
				}
				//身份证反面
				MerchantUserUploadVo backVo = new MerchantUserUploadVo();
				backVo.setP1_bizType("UploadCredential");
				backVo.setP3_orderId(IdUtil.simpleUUID());
				backVo.setP4_userId(StrUtil.toString(data.get("userId")));
				backVo.setP6_credentialType("BACK_OF_ID_CARD");
				HlbReturnDTO backResult = HlbPayUtil.userUpload(backVo, attachList.get(0).getLaAttachmentDTOList().get(1).getFileLocation());
				if(!StrUtil.equals(backResult.getCode(), "0")){
					result.put("result", "-1");
	        		result.put("errorCode", MarvelsConstant.FAILED);
					result.put("errorMsg", "用户资质【反面】上传失败");
					return result;
				}
			} catch (Exception e) {
				result.put("result", "-1");
        		result.put("errorCode", MarvelsConstant.FAILED);
				result.put("errorMsg", "用户资质上传异常");
				return result;
			}
			// 资质上传成功之后，默认等待用户审核
			result.put("result", "1");
    		result.put("errorCode", MarvelsConstant.PROCESSING);
    		result.put("errorMsg", "等待审核");
    		return result;
		}
	}

	/**
	 * 查询代付结果
	 */
	@Override
	public Map<String, Object> payResultQuery(McfeRepaymentTradeDetails tradeDetail) {
		Map<String, Object> result = new HashMap<String, Object>();
		// 根据订单号查询结果
		String payOrderNumber = tradeDetail.getPayOrderNumber();
		// 查询代付结果
		if(payOrderNumber.startsWith("HLBDF")){
			HlbConfig hlbConfig = HlbConfig.getInstance(HlbConfig.DF);
			McfeHlbUserInfo mcfeHlbUserInfo = hlbUserInfoMapper.querySuccessByIdCard(tradeDetail.getIdNumber(), hlbConfig.getMerchantNo());
			if(mcfeHlbUserInfo != null){
				tradeDetail.setHlbUserId(mcfeHlbUserInfo.getUserId());
			}
			return HlbPayUtil.payResultQuery(tradeDetail);
		}
		
		// 查询注册结果
		if(payOrderNumber.startsWith("HLBZC")){
			McfeHlbUserInfo mcfeHlbUserInfo = hlbUserInfoMapper.queryByOrderId(payOrderNumber);
			if(mcfeHlbUserInfo != null){
				tradeDetail.setHlbUserId(mcfeHlbUserInfo.getUserId());
			}
			HlbReturnDTO queryResult = HlbPayUtil.userQuery(tradeDetail);
			// 修改数据数据
			Map<String, Object> data = (Map<String, Object>) queryResult.getData();
			mcfeHlbUserInfo.setOrderId(tradeDetail.getPayOrderNumber());
			mcfeHlbUserInfo.setStatus(data == null ? null : data.get("userStatus").toString());
			mcfeHlbUserInfo.setUserId(data == null ? null : data.get("userId").toString());
			hlbUserInfoMapper.updateByOrderIdSelective(mcfeHlbUserInfo);
			// 用户没有注册成功，不触发代付
			if(!StrUtil.equals(queryResult.getCode(), "0")){
				result.put("result", queryResult.getCode());
				result.put("errorCode", MarvelsConstant.SUCCESS);
				result.put("errorMsg", queryResult.getMsg());
				return result;
			}
			
			// 注册成功了，再调用代付接口
			String dfOrderNumber = GenerateReqNoUtils.transctionReq2("HLBDF",24);
			tradeDetail.setPayOrderNumber(dfOrderNumber);
			tradeDetail.setHlbUserId(mcfeHlbUserInfo.getUserId());
			// 生成了代付订单先修改订单表状态，以免并发导致其他服务器又重复跑单
			McfeRepaymentTradeDetails tradeDetails = new McfeRepaymentTradeDetails();
			tradeDetails.setId(tradeDetail.getId());
			tradeDetails.setPayOrderNumber(dfOrderNumber);
			int num = mcfeRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(tradeDetails);
			if(num > 0){
				result = HlbPayUtil.pay(tradeDetail);
				result.put("dfOrderNumber", dfOrderNumber);
			}else{
				result.put("result", "-1");
        		result.put("errorCode", MarvelsConstant.FAILED);
				result.put("errorMsg", "注册成功，但回写代付订单号失败");
			}
			return result;
		}
		
		result.put("result", "1");
		result.put("errorCode", MarvelsConstant.SUCCESS);
		result.put("errorMsg", "非法订单号");
		return result;
	}
	
	

}
